package com.micai.boss.sms.provider.yimei;

import com.micai.boss.sms.url.ProviderUrl;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HTTP;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * 描述：
 * <p>
 *
 * @author: 赵新国
 * @date: 2018/4/24 13:13
 */
@Component
public class YimeiSMSInterfaceUtil {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    /*
     * 一客一签通道，客户在移动端申请的专用、独占的通道，响应时间快（5秒以内） 自定义通道，普通通道，响应时间慢(10秒)左右
     */
    private final String SIGNED_ACCOUNT = "9SDK-EMY-0999-RGQNN";
    private final String SIGNED_PSWD    = "546125";

    private String host = ProviderUrl.yimeiurl;

    private String getBatchURL() {
        return host + "/sendsms.action";
    }
    private String getCdkeyRegistURL() {
        return host + "/regist.action";
    }
    private String getRegistDetailInfoURL() {
        return host + "/registdetailinfo.action";
    }

    public ResponseObject sendBatchSignedMsg(String[] mobiles, String msg) {
        return sendMsg(getBatchURL(), SIGNED_ACCOUNT, SIGNED_PSWD, msg, mobiles);
    }

    public ResponseObject cdkeyRegist() {
        return cdkeyFirstRegist(getCdkeyRegistURL(), SIGNED_ACCOUNT, SIGNED_PSWD);
    }

    public ResponseObject registDetailInfo() {
        return firstRegistDetailInfo(getRegistDetailInfoURL(), SIGNED_ACCOUNT, SIGNED_PSWD);
    }

    private ResponseObject sendMsg(String url, String account, String password, String content, String... mobiles) {
        if (mobiles == null || mobiles.length == 0 || mobiles.length > 50000 || content == null
                || content.trim().isEmpty()) {
            throw new RuntimeException("传入参数错误，请检查");
        }
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse httpResponse = null;
        try {
            String requestContent = getRequestContent(account, password, mobiles, content);
            HttpPost post = new HttpPost(url);
            post.setHeader(HTTP.CONTENT_TYPE, URLEncodedUtils.CONTENT_TYPE);
            post.setEntity(new StringEntity(requestContent));
            httpResponse = httpClient.execute(post);
            return parseResponse(httpResponse);
        } catch (Exception e) {
            logger.error("发送短信时出错", e);
            return new ResponseObject(System.currentTimeMillis() + "", "500", "");
        } finally {
            try {
                httpClient.close();
            } catch (Exception e) {
            }
            if (httpResponse != null) {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                }
            }
        }
    }
    private ResponseObject cdkeyFirstRegist(String url, String account, String password) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse httpResponse = null;
        try {
            String requestContent = getCdkeyRequestContent(account, password);
            HttpPost post = new HttpPost(url);
            post.setHeader(HTTP.CONTENT_TYPE, URLEncodedUtils.CONTENT_TYPE);
            post.setEntity(new StringEntity(requestContent));
            httpResponse = httpClient.execute(post);
            return parseResponse(httpResponse);
        } catch (Exception e) {
            logger.error("序列号注册失败", e);
            return new ResponseObject(System.currentTimeMillis() + "", "500", "");
        } finally {
            try {
                httpClient.close();
            } catch (Exception e) {
            }
            if (httpResponse != null) {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                }
            }
        }
    }

    private ResponseObject firstRegistDetailInfo(String url, String account, String password) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse httpResponse = null;
        try {
            String requestContent = getDetailInfoRequestContent(account, password);
            HttpPost post = new HttpPost(url);
            post.setHeader(HTTP.CONTENT_TYPE, URLEncodedUtils.CONTENT_TYPE);
            post.setEntity(new StringEntity(requestContent));
            httpResponse = httpClient.execute(post);
            return parseResponse(httpResponse);
        } catch (Exception e) {
            logger.error("注册企业信息失败", e);
            return new ResponseObject(System.currentTimeMillis() + "", "500", "");
        } finally {
            try {
                httpClient.close();
            } catch (Exception e) {
            }
            if (httpResponse != null) {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                }
            }
        }
    }

    private ResponseObject parseResponse(CloseableHttpResponse httpResponse) throws Exception {
        BufferedReader br = null;
        try {
            if (httpResponse.getStatusLine() == null || httpResponse.getStatusLine().getStatusCode() != 200) {
                return new ResponseObject(System.currentTimeMillis() + "", "400", "");
            }
            HttpEntity entity = httpResponse.getEntity();
            InputStream resInputStream = entity.getContent();
            if (resInputStream == null) {
                new ResponseObject(System.currentTimeMillis() + "", "600", "");
            }
            br = new BufferedReader(new InputStreamReader(resInputStream));
            String readLine = br.readLine();
            StringBuilder sb = new StringBuilder();
            while (readLine != null ) {
                if(StringUtils.isNotBlank(readLine)){
                    sb.append(readLine);
                }
                readLine = br.readLine();
            }
            String responseContent = sb.toString();
            SAXReader saxReader = new SAXReader();
            Document doc = saxReader.read(new ByteArrayInputStream(responseContent.getBytes("UTF-8")));
            Element root = doc.getRootElement();
            List<Element> list= root.elements();
            if(list != null && list.size() > 0){
                return new ResponseObject(System.currentTimeMillis()+"", list.get(0).getStringValue() , null);
            }
            return null;
        } finally {
            if (br != null) {
                if (br != null) {
                    try {
                        br.close();
                    } catch (IOException e) {
                    }
                }
            }
        }
    }

    private String getRequestContent(String account, String password, String[] mobiles, String content) throws UnsupportedEncodingException {
        Map<String, String> contentMap = new HashMap<>();
        contentMap.put("cdkey", account);// 必填参数。用户序列号
        contentMap.put("password", password);// 必填参数。用户密码
        contentMap.put("phone", array2String(mobiles));// 必填参数。手机号码（最多200个），多个用英文逗号(,)隔开。
        //必填参数。短信内容（UTF-8编码）（最多500个汉字或1000个纯英文）。
        contentMap.put("message", content);
        //附加号。（最长10位，可置空）。
        contentMap.put("addserial", "");
        return encode(contentMap);
    }

    private String getCdkeyRequestContent(String account, String password) throws UnsupportedEncodingException {
        Map<String, String> contentMap = new HashMap<>();
        contentMap.put("cdkey", account);// 必填参数。用户序列号
        contentMap.put("password", password);// 必填参数。用户密码
        return encode(contentMap);
    }

    private String getDetailInfoRequestContent(String account, String password) throws UnsupportedEncodingException {
        Map<String, String> contentMap = new HashMap<>();
        contentMap.put("cdkey", account);// 必填参数。用户序列号
        contentMap.put("password", password);// 必填参数。用户密码
        contentMap.put("ename", "北京XXX公司");//
        contentMap.put("linkman", "赵XX");//
        contentMap.put("phonenum", "010-11111111");//
        contentMap.put("mobile", "13000000000");//
        contentMap.put("email", "13000000000@139.com");//
        contentMap.put("fax", "11111111");//
        contentMap.put("address", "北京市XXX");//
        contentMap.put("postcode", "100000");//
        return encode(contentMap);
    }

    private String array2String(String[] mobiles) {
        if (mobiles == null) {
            return null;
        }
        if (mobiles.length == 0) {
            return "";
        }
        if (mobiles.length == 1) {
            return mobiles[0];
        }
        StringBuilder sb = new StringBuilder();
        sb.append(mobiles[0]);
        for (int i = 1; i < mobiles.length; i++) {
            sb.append(",");
            sb.append(mobiles[i]);
        }
        return sb.toString();
    }

    private String encode(Map<String, String> queries) throws UnsupportedEncodingException {
        if (queries == null || queries.isEmpty()) {
            return null;
        }
        Set<String> keySet = queries.keySet();
        StringBuilder sb = new StringBuilder();
        for (String s : keySet) {
            sb.append("&");
            sb.append(s);
            sb.append("=");
            sb.append(URLEncoder.encode(queries.get(s), "UTF-8"));
        }
        return sb.substring(1);
    }
}
